<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>测试getusermedia</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>

    <div>
        <audio id="playDemo" controls="controls"></audio>
    </div>
    <div>
        <button type="button" id="start">开始录音</button>
        <button type="button" id="stop">停止录音</button>
        <button type="button" id="pause">暂停录音</button>
    </div>
    <div id="soundClips">

    </div>
    <script>
        var chunks = [];
        // Older browsers might not implement mediaDevices at all, so we set an empty object first
        if (navigator.mediaDevices === undefined) {
            navigator.mediaDevices = {};
        }

        // Some browsers partially implement mediaDevices. We can't just assign an object
        // with getUserMedia as it would overwrite existing properties.
        // Here, we will just add the getUserMedia property if it's missing.
        if (navigator.mediaDevices.getUserMedia === undefined) {
            navigator.mediaDevices.getUserMedia = function (constraints) {

                // First get ahold of the legacy getUserMedia, if present
                var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

                // Some browsers just don't implement it - return a rejected promise with an error
                // to keep a consistent interface
                if (!getUserMedia) {
                    return Promise.reject(new Error('您的浏览器不支持在线录音，建议您使用最新版的Chrome浏览器。'));
                }

                // Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
                return new Promise(function (resolve, reject) {
                    getUserMedia.call(navigator, constraints, resolve, reject);
                });
            }
        }

        navigator.mediaDevices.getUserMedia({ audio: true })
            .then(function (stream) {
                console.log(stream);
                // var playAudio = document.getElementById("playDemo");
                // var url = window.URL.createObjectURL(stream);
                // playAudio.src = url;

                /**
                 * 使用MediaRecorder录音
                 * Feature	Chrome	Firefox (Gecko)	Internet Explorer	Opera	Safari (WebKit)
                 * Basic 	47.0	25.0 (25.0)	    未实现	            未实现	 未实现
                 */
                var mediaRecorder = new MediaRecorder(stream);

                mediaRecorder.ondataavailable = function (e) {
                    chunks.push(e.data);
                }

                mediaRecorder.onstop = function (e) {
                    console.log("data available after MediaRecorder.stop() called.");
                    var audio = document.getElementById("playDemo");
                    // audio.setAttribute('controls', '');
                    audio.controls = true;
                    var blob = new Blob(chunks, { 'type': 'audio/wav; codecs=opus' });
                    chunks = [];
                    var audioURL = URL.createObjectURL(blob);
                    console.log("audioURL: ",audioURL);
                    audio.src = audioURL;
                    console.log("recorder stopped");
                }

                $("#start").on("click", function () {
                    var state = mediaRecorder.state;
                    if(state === "paused"){
                        mediaRecorder.resume();
                    }else{
                        mediaRecorder.start();
                    }
                    console.log("recorder started");
                });

                $("#stop").on("click", function () {
                    mediaRecorder.stop();
                    console.log(mediaRecorder.state);
                    console.log("recorder stopped");
                });

                $("#pause").on("click", function () {
                    mediaRecorder.pause();
                    console.log(mediaRecorder.state);
                    console.log("recorder pause");
                });


            })
            .catch(function (err) {
                switch (err.name) {
                    case 'NotAllowedError':
                    case 'PermissionDeniedError':
                        alert("用户已禁止网页调用录音设备.");
                        break;
                    case 'NotFoundError':
                    case 'DevicesNotFoundError':
                        alert("未找到音频输入设备");
                    case 'NotSupportedError':
                        alert("您的浏览器不支持录音功能，建议使用最新版的Chrome浏览器。");
                    case "AbortError":
                        alert("访问输入设备出现异常");
                        break;
                }
                console.log(err.name + ": " + err.message);
            });
    </script>
</body>

</html>